package com.roy.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/3
 * @description:
 **/

public class NioClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        final SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("连接建立中。这里与网速有关");
            }
        }
        Scanner scanner =new Scanner(System.in);
        while(scanner.hasNextLine()){
            final String message = scanner.next();
            if("q".equals(message)){
                socketChannel.close();
                System.exit(0);
            }
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
            Thread.sleep(1000);
            ByteBuffer responseBuffer = ByteBuffer.allocate(512);
            socketChannel.read(responseBuffer);
            System.out.println("收到服务器的响应:" + new String(responseBuffer.array()) + ";按任意键继续发送消息");

        }
    }
}
